<?php
/*
 * @Author: cwj
 * @Date: 2019-12-13 16:13:22
 * @LastEditTime : 2020-01-21 14:54:54
 * @LastEditors  : Please set LastEditors
 * @Description: 修改 异步方式
 * @FilePath: /ahsmp_3/application/asmpasync/socket/SocketClient.php
 */
namespace app\asmpasync\socket;


class SocketClient
{
    private $socket;
    public $feedback = '';
    public $error_id = 0;
    public $err_msg = 0;
    public $sendStatus;

    public function __construct($ip = '127.0.0.1', $port = 9007)
    {
        $context = stream_context_create([
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
            ]
        ]);
        $this->socket = @stream_socket_client( 'tlsv1.2://' . $ip . ':' . $port, $this->error_id, $this->err_msg, 10, STREAM_CLIENT_CONNECT, $context);
    }

    /**
     * 发送信息
     *
     * @return array
     * [
     *      'status' =>  bool
     *      'message' => string
     *      'is_socket_error' => 是否为socket错误
     * ]
     */
    public function sendMsg ($msg)
    {
        if ($this->error_id > 0)
        {
            $this->err_msg = 'socket连接失败->'.$this->err_msg;
            return [
                'status' => false,
                'message' => $this->err_msg,
                'is_socket_error' => true
            ];
        }

        //如果连接失败,返回错误信息
        if(!$this->socket){
            $msg = iconv('GB2312', 'UTF-8', $this->err_msg); //将字符串的编码从GB2312转到UTF-8
            if($msg){
                $this->err_msg = 'socket连接失败->'.$msg;
            }else{
                $this->err_msg = 'socket连接失败';
            }
            return [
                'status' => false,
                'message' => $this->err_msg,
                'is_socket_error' => true
            ];
        }

        fwrite($this->socket, $msg);
        $response = $this->feedback();

        fclose($this->socket);

        return $response;
    }

    /**
     * 获取响应
     *
     * @return array
     * [
     *      'status' =>  bool
     *      'message' => string
     * ]
     */
    public function feedback ()
    {
        $serverBack = fread($this->socket, 4096);
        if(!$serverBack){
            return [
                'status' => false,
                'message' => '没有响应数据,请核查通信IP、端口是否正确',
                'is_socket_error' => false
            ];
        }
        $len = unpack('ilen', substr($serverBack, 0, 4));
        $data = substr($serverBack, 6, $len['len']);
        $Event = new \Asmpproto\Event();
        $Event->mergeFromString($data);
        $Result = $Event->getMessage();
        $message = $Result->unpack();
        //发送状态
        $this->sendStatus = $message->getStatus();
        return [
            'status' => $this->sendStatus,
            'message' => '响应信息->' .$message->getMessage(),
            'is_socket_error' => false
        ];

    }
}